﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Xml;
using System.Xml.Linq;

namespace Alma.Core
{
    public struct BingLocation
    {
        public double X;
        public double Y;
    }

    public static class BingMaps
    {
        private const string ApiKey = "AkCZ5m1WEQHmCI_IGnizvsQwwuocz4MVzwE7AI5t7nO8yrqo-18MfLem2Jyq4F8p";

        public static BingLocation Localize(string address, string city, string country)
        {
            var target = address + ", " + city + ", " + country;

            using(var xml =
                new XmlTextReader(
                    "http://dev.virtualearth.net/REST/v1/Locations/" + HttpUtility.UrlPathEncode(target) +
                    "?output=xml&key=" + ApiKey))
            {

                var doc = XDocument.Load(xml);
                var ns = XNamespace.Get("http://schemas.microsoft.com/search/local/ws/rest/v1");
                var bloc = new BingLocation();

                try
                {
                    var loc = doc.Root.Element(ns + "ResourceSets")
                        .Element(ns + "ResourceSet")
                        .Element(ns + "Resources")
                        .Element(ns + "Location");

                    var point = loc.Element(ns + "Point");
                    bloc.X = double.Parse(point.Element(ns + "Latitude").Value, CultureInfo.InvariantCulture);
                    bloc.Y = double.Parse(point.Element(ns + "Longitude").Value, CultureInfo.InvariantCulture);
                }
                catch(NullReferenceException)
                {
                }

                return bloc;
            }
        }
    }
}
